package com.dgut.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dgut.admin.param.LoginParam;
import com.dgut.admin.param.PasswordParam;
import com.dgut.admin.result.LoginResult;
import com.dgut.admin.service.AdminUserService;
import com.dgut.common.entity.AdminUser;
import com.dgut.common.mapper.AdminUserMapper;
import com.dgut.common.utils.ApiException;
import com.dgut.common.utils.ErrorEnum;
import com.dgut.common.utils.JwtUtil;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author it00zyq
 * @date 2022/1/8
 */
@Service
public class AdminUserServiceImpl implements AdminUserService {

    private final AdminUserMapper adminUserMapper;
    public AdminUserServiceImpl(AdminUserMapper adminUserMapper) {
        this.adminUserMapper = adminUserMapper;
    }

    @Override
    public LoginResult login(LoginParam param) {
        // 检查密码
        QueryWrapper<AdminUser> wrapper = new QueryWrapper<>();
        wrapper.eq("username", param.getUsername());
        AdminUser adminUser = adminUserMapper.selectOne(wrapper);
        if (adminUser == null || !adminUser.getPassword().equals(param.getPassword())) {
            throw new ApiException(ErrorEnum.USERNAME_OR_PASSWORD_ERROR);
        }

        // 生成token
        String token = JwtUtil.getToken(adminUser.getUsername());

        return LoginResult.builder()
                .token(token)
                .username(adminUser.getUsername())
                .build();
    }

    @Override
    public void updatePassword(PasswordParam param, String token) {
        AdminUser admin = JwtUtil.getAdmin(token);

        // 检查原密码是否正确
        if (!admin.getPassword().equals(param.getOldPassword())) {
            throw new ApiException(ErrorEnum.PASSWORD_CHECK_ERROR);
        }

        admin.setPassword(param.getNewPassword());
        adminUserMapper.updateById(admin);
    }
}
